<template>
  <base-table-layout title="农户需求管理" :total="total" :current-page="currentPage" :page-size="pageSize"
    @update:currentPage="val => currentPage = val" @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange" @current-change="handleCurrentChange">
    <!-- 搜索区域 -->
    <template #search>
      <el-input v-model="searchForm.keyword" placeholder="请输入农户姓名/烟草品种/备注信息" style="width: 300px;" class="filter-item"
        @keyup.enter.native="handleSearch">
        <template slot="prepend">
          <i class="el-icon-search"></i>
        </template>
      </el-input>
      <dept-tree-select
        v-model="searchForm.deptId"
        placeholder="选择部门"
        width="300px"
        class="filter-item"
        @change="handleSearch"
      />
      <el-select v-model="searchForm.status" placeholder="状态" clearable class="filter-item" style="width: 120px">
        <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button class="filter-item" type="info" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增需求</el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="!selectedDemands.length"
        @click="handleBatchDelete">批量删除</el-button>
      <el-button type="primary" icon="el-icon-s-operation" :disabled="!selectedDemands.length"
        @click="handleBatchCreateOrder">生成订单</el-button>
      <div v-if="selectedDemands.length" style="display: inline-block; margin-left: 10px;">
        已选择 {{ selectedDemands.length }} 条记录
      </div>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <div class="table-container">
        <el-table v-loading="loading" :data="demandList" border style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="demandId" label="需求ID" width="100" />
          <el-table-column prop="growerName" label="农户名称" width="120" />
          <el-table-column label="所属部门" min-width="250">
            <template slot-scope="scope">
              <el-tag size="mini" type="success" style="margin-left: 5px">{{ scope.row.townName }}</el-tag>
              <el-tag size="mini" type="warning" style="margin-left: 5px">{{ scope.row.villageGroupName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="seedlingType" label="烟苗类型" width="120" />
          <el-table-column prop="quantity" label="需求数量(亩)" width="120" />
          <el-table-column prop="plateQuantity" label="盘数" width="120" />
          <el-table-column label="需求日期" width="180">
            <template slot-scope="scope">
              {{ scope.row.demandTime }}
            </template>
          </el-table-column>
          <el-table-column prop="statusDesc" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.statusDesc }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="250" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" :disabled="scope.row.status !== 0"
                @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" :disabled="scope.row.status !== 0"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-footer">
          <div class="total-area">总计: {{ totalArea }}亩 ({{ totalPlates }}盘)</div>
        </div>
      </div>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="农户" prop="growerId">
            <el-input v-model="selectedGrowerName" placeholder="请选择农户" readonly style="width: 100%"
              @click.native="showGrowerSelectDialog" />
          </el-form-item>
          <el-form-item label="烟苗类型" prop="seedlingType">
            <el-select v-model="form.seedlingType" placeholder="请选择或输入烟苗类型" style="width: 100%" filterable allow-create
              default-first-option>
              <el-option label="膜下苗" value="膜下苗" />
              <el-option label="水稻秧苗" value="水稻秧苗" />
              <el-option label="烤烟" value="烤烟" />
            </el-select>
          </el-form-item>
          <el-form-item label="需求日期" prop="demandTime">
            <el-date-picker v-model="form.demandTime" type="date" placeholder="选择日期" style="width: 100%"
              value-format="yyyy-MM-dd" :picker-options="{
                disabledDate(time) {
                  return time.getTime() < Date.now() - 8.64e7;
                }
              }" />
          </el-form-item>
          <el-form-item label="需求数量" prop="quantity">
            <el-input-number v-model="form.quantity" :min="1" style="width: 100%" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>

      <!-- 使用农户选择组件 -->
      <grower-select 
        :visible.sync="growerSelectVisible"
        @select="handleGrowerSelect"
      />

      <!-- 进度条对话框 -->
      <el-dialog title="处理进度" :visible.sync="progressVisible" :close-on-click-modal="false"
        :close-on-press-escape="false" :show-close="false" width="600px" class="progress-dialog">
        <div class="progress-content">
          <el-progress :percentage="progressPercentage" :format="percent => `${percent}%`" :stroke-width="24"
            class="custom-progress" />
          <div class="progress-text">{{ progressText }}</div>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import moment from 'moment'
import 'moment/locale/zh-cn'
import BaseTableLayout from '@/components/BaseTableLayout.vue'
import { sleep } from '@/utils'
import DeptTreeSelect from '@/components/DeptTreeSelect.vue'
import GrowerSelect from '@/components/GrowerSelect.vue'

export default {
  name: 'SeedlingDemand',
  components: {
    BaseTableLayout,
    DeptTreeSelect,
    GrowerSelect
  },
  data() {
    return {
      loading: false,
      searchForm: {
        keyword: undefined,
        status: undefined,
        deptId: undefined
      },
      statusOptions: [
        { label: '待分配', value: 0 },
        { label: '已生成订单', value: 1 },
        { label: '已分配育苗点', value: 2 },
        { label: '已分配司机', value: 3 },
        { label: '配送中', value: 4 },
        { label: '已完成', value: 5 },
        { label: '已退单', value: 6 },
        { label: '已取消', value: 7 }
      ],
      demandList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      isEdit: false,
      currentId: null,
      form: {
        growerId: undefined,
        seedlingType: '',
        demandTime: '',
        quantity: 5,
        remark: ''
      },
      rules: {
        growerId: [
          { required: true, message: '请选择农户', trigger: 'change' }
        ],
        seedlingType: [
          { required: true, message: '请选择烟苗类型', trigger: 'change' }
        ],
        demandTime: [
          { required: true, message: '请选择需求日期', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入需求数量', trigger: 'blur' }
        ]
      },
      selectedGrowerName: '',
      growerSelectVisible: false,
      selectedDemands: [],
      progressVisible: false,
      progressText: '',
      progressPercentage: 0
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑需求' : '新增需求'
    },
    totalArea() {
      return this.demandList.reduce((sum, item) => {
        const value = Number(item.quantity)
        return sum + (isNaN(value) ? 0 : value)
      }, 0).toFixed(2)
    },
    totalPlates() {
      return this.demandList.reduce((sum, item) => {
        const value = Number(item.plateQuantity)
        return sum + (isNaN(value) ? 0 : value)
      }, 0)
    }
  },
  created() {
    moment.locale('zh-cn')
    this.fetchDemandList()
  },
  methods: {
    // 获取需求列表
    async fetchDemandList() {
      try {
        this.loading = true
        const response = await request.get('/seedling/demands/page', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            keyword: this.searchForm.keyword,
            status: this.searchForm.status,
            deptId: this.searchForm.deptId
          }
        })

        if (response.records) {
          this.demandList = response.records
          this.total = response.total
        }
      } catch (error) {
        console.error('获取需求列表失败:', error)
        this.$message.error('获取需求列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch: _.debounce(async function () {
      this.currentPage = 1
      await this.fetchDemandList()
    }, 300),

    resetQuery() {
      this.searchForm = {
        keyword: undefined,
        status: undefined,
        deptId: undefined
      }
      this.currentPage = 1
      this.fetchDemandList()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchDemandList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchDemandList()
    },

    // 显示农户选择对话框
    showGrowerSelectDialog() {
      this.growerSelectVisible = true
    },

    // 处理农户选择
    handleGrowerSelect(grower) {
      this.form.growerId = grower.growerId
      this.selectedGrowerName = `${grower.growerName}(${grower.deptName})`
    },

    // 显示新增对话框
    handleAdd() {
      this.isEdit = false
      this.currentId = null
      const tomorrow = moment().add(1, 'days')
      this.form = {
        growerId: undefined,
        seedlingType: '',
        demandTime: tomorrow.format('YYYY-MM-DD'),
        quantity: 5,
        remark: ''
      }
      this.selectedGrowerName = ''
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },

    // 显示编辑对话框
    handleEdit(row) {
      this.isEdit = true
      this.currentId = row.demandId
      this.form = {
        growerId: row.growerId,
        seedlingType: row.seedlingType,
        demandTime: row.demandTime,
        quantity: row.quantity,
        remark: row.remark
      }
      this.selectedGrowerName = row.growerName
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },

    // 删除需求
    handleDelete(row) {
      this.$confirm('确认删除该需求吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await request.delete(`/seedling/demands/${row.demandId}`)
          this.$message.success('删除成功')
          this.fetchDemandList()
        } catch (error) {
          console.error('删除需求失败:', error)
          this.$message.error('删除需求失败')
        }
      }).catch(() => { })
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        if (this.isEdit) {
          await request.put(`/seedling/demands`, {
            demandId: this.currentId,
            ...this.form
          })
          this.$message.success('编辑成功')
        } else {
          await request.post('/seedling/demands', this.form)
          this.$message.success('添加成功')
        }
        this.dialogVisible = false
        this.fetchDemandList()
      } catch (error) {
        if (error !== false) {
          console.error(this.isEdit ? '编辑需求失败:' : '添加需求失败:', error)
          this.$message.error(this.isEdit ? '编辑需求失败' : '添加需求失败')
        }
      }
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'warning',   // 待分配
        1: 'primary',   // 已生成订单
        2: 'success',   // 已分配育苗点
        3: 'info',      // 已分配司机
        4: 'warning',   // 配送中
        5: 'success',   // 已完成
        6: 'danger',    // 已退单
        7: 'info'       // 已取消
      }
      return statusMap[status] || 'info'
    },

    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedDemands = selection
    },

    // 批量删除
    async handleBatchDelete() {
      try {
        await this.$confirm('确认删除选中的需求吗？此操作不可恢复！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const totalDemands = this.selectedDemands.length
        let processedDemands = 0

        this.showProgress('正在删除数据...')

        let successCount = 0
        let failCount = 0

        for (const demand of this.selectedDemands) {
          try {
            await request.delete(`/seedling/demands/${demand.demandId}`)
            successCount++
          } catch (error) {
            console.error(`删除需求${demand.demandId}失败:`, error)
            failCount++
          }

          processedDemands++
          this.updateProgress(processedDemands, totalDemands)

          await sleep(500)
        }

        this.closeProgress()

        this.$message({
          type: successCount > 0 ? (failCount === 0 ? 'success' : 'warning') : 'error',
          message: `删除完成：成功${successCount}条${failCount > 0 ? `，失败${failCount}条` : ''}`
        })

        this.fetchDemandList()
      } catch (error) {
        this.closeProgress()
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },

    // 批量生成订单
    async handleBatchCreateOrder() {
      try {
        if (!this.selectedDemands.length) {
          this.$message.warning('请选择要生成订单的需求')
          return
        }

        await this.$confirm('确认将选中的需求生成订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const demandIds = this.selectedDemands.map(demand => demand.demandId)
        await request.post('/seedling/orders', {
          demandIds,
          remark: '批量生成订单'
        })

        this.$message.success('订单生成成功')
        this.fetchDemandList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('生成订单失败:', error)
          this.$message.error('生成订单失败')
        }
      }
    },

    // 显示进度条
    showProgress(text) {
      this.progressVisible = true
      this.progressText = text
      this.progressPercentage = 0
    },

    // 更新进度
    updateProgress(current, total) {
      this.progressPercentage = Math.floor((current / total) * 100)
    },

    // 关闭进度条
    closeProgress() {
      this.progressVisible = false
      this.progressText = ''
      this.progressPercentage = 0
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.filter-item {
  margin-left: 10px;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
}

.table-container {
  position: relative;
}

.table-footer {
  position: absolute;
  left: 0;
  bottom: -40px;
  z-index: 1;
}

.total-area {
  font-size: 14px;
  color: #606266;
  font-weight: bold;
  padding: 10px 0;
}

.progress-dialog {
  :deep(.el-dialog) {
    width: 600px !important;

    .el-dialog__body {
      padding: 30px;
    }
  }

  .progress-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;

    .custom-progress {
      width: 100%;
      margin-bottom: 20px;

      :deep(.el-progress-bar__outer) {
        height: 24px !important;
        background-color: #EBEEF5;
        border-radius: 12px;
      }

      :deep(.el-progress-bar__inner) {
        background-color: #409EFF;
        border-radius: 12px;
        transition: width 0.3s ease;
      }

      :deep(.el-progress__text) {
        font-size: 18px;
        color: #409EFF;
        font-weight: bold;
        margin-left: 10px;
      }
    }

    .progress-text {
      font-size: 16px;
      color: #606266;
      margin-top: 15px;
      text-align: center;
    }
  }
}
</style>